import { HttpError, toSuccess, useEntityManager } from "@sker/core"
import { useData } from "@sker/runtime"
import { AutoDevice } from "@sker/entities"
import { z } from "zod"
import { FindOptionsWhere } from "typeorm"


export default async () => {
    const input = z.object({
        page: z.number(),
        token: z.string(),
        status: z.string()
    })
    const body = input.parse(useData())
    const psize = 20;
    const where: FindOptionsWhere<AutoDevice> = {};
    if (body.status !== `all`) {
        where.status = body.status === 'online' ? `1` : `0`
    }
    const list = await useEntityManager(async m => {
        const device = await m.findOne(AutoDevice, { where: { token: body.token } })
        if (!device) throw new HttpError(`设备不存在`)
        where.uid = device.uid;
        return await m.find(AutoDevice, {
            select: {
                device_name: true,
                id: true,
                status: true,
                ping_time: true
            }, where: where, take: psize, skip: (body.page - 1) * psize
        })
    })
    return toSuccess(list)
}